import { ref, computed, onMounted } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies'
import { router } from '@/router'

export function useFTagList() {
  const route = useRoute()
  const cookie = useCookies()

  const activeTab = ref(route.path)
  const tabList = ref([
    {
      title: '后台首页',
      path: '/',
    },
  ])

  // 初始化标签导航列表
  const initTabList = () => {
    let tbs = cookie.get('tabList')
    if (tbs) {
      tabList.value = tbs
    }
  }

  initTabList()

  onBeforeRouteUpdate((to, from) => {
    activeTab.value = to.path
    addTab({
      title: to.meta.title,
      path: to.path,
    })
  })

  const addTab = (tab) => {
    let noTab = tabList.value.findIndex((t) => t.path === tab.path) === -1
    if (noTab) {
      tabList.value.push(tab)
    }
    cookie.set('tabList', tabList.value)
  }

  const removeTab = (t) => {
    let a = activeTab.value
    let tabs = tabList.value
    if (a === t) {
      tabs.forEach((tab, index) => {
        if (tab.path === t) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            a = nextTab.path
          }
        }
      })
    }

    activeTab.value = a
    tabList.value = tabs.filter((tab) => tab.path !== t)
    cookie.set('tabList', tabList.value)
  }

  const handleTabChange = (name) => {
    activeTab.value = name
    router.push(name)
  }

  const handleClose = (command) => {
    console.log(command, 'command')
    switch (command) {
      case 'clearOther':
        clearOther()
        break
      case 'clearAll':
        clearAll()
        break
    }
  }

  const clearOther = () => {
    tabList.value = tabList.value.filter(
      (tab) => tab.path === activeTab.value || tab.path === '/'
    )
    cookie.set('tabList', tabList.value)
  }

  const clearAll = () => {
    activeTab.value = '/'
    tabList.value = [
      {
        title: '后台首页',
        path: '/',
      },
    ]
    cookie.set('tabList', tabList.value)
  }

  return {
    activeTab,
    tabList,
    removeTab,
    handleTabChange,
    handleClose,
  }
}
